package com.goodflower.goodflower;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.signature.StringSignature;
import com.goodflower.goodflower.address.Address;
import com.goodflower.goodflower.chang_user.Change_user_password;
import com.goodflower.goodflower.chang_user.Change_user_phone;
import com.goodflower.goodflower.chang_user.Change_user_touxiang;
import com.goodflower.goodflower.creat_mac.Creat_mac_one;
import com.goodflower.goodflower.info.Info;
import com.goodflower.goodflower.util.HttpUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.HttpUrl;
import okhttp3.Response;

public class FlowerActivity extends AppCompatActivity {
    private DrawerLayout drawerLayout;
    private Button btn_home;
    private TextView flower_title;
    private String user_name;
    private Flower flowers[] = {};
    private List<Flower> flowerList = new ArrayList<>();
    private FlowerAdapter flowerAdapter;
    private SwipeRefreshLayout swipeRefresh;
    private FloatingActionButton float_btn;

    private void refreshFlower() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        huoquflower();

                    }
                });
            }
        }).start();
    }

    private void huoquflower() {
        flowerList.clear();

        HttpUtil.sendOkHttpRequest("http://"+Info.server_ip+"/huahua/huoquuser.php?username=" + user_name, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String myflowerRerson = response.body().string();

                try {
                    // JSONArray jsonArray = new JSONArray(myflowerRerson);
                    // JSONObject jsonObject = jsonArray.getJSONObject(0);

                    JSONObject jsonObject = new JSONObject(myflowerRerson);
                    String json_username = jsonObject.getString("username");
                    String json_flowers = jsonObject.getString("flowers");
                    if(!json_flowers.isEmpty()){
                        String[] all_flowers = json_flowers.split("\\|");

                        for (String line : all_flowers) {
                            Flower linshi_flower = new Flower(jsonObject.getString(line), line, json_username);
                            flowerList.add(linshi_flower);
                        }
                        if (swipeRefresh != null) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    flowerAdapter.notifyDataSetChanged();
                                    swipeRefresh.setRefreshing(false);
                                }
                            });
                        }
                    }else {
                        if (swipeRefresh != null) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    flowerAdapter.notifyDataSetChanged();
                                    swipeRefresh.setRefreshing(false);
                                }
                            });
                        }
                    }



                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_flower);
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        /***chushihua*/

        final ImageView icon = (ImageView) navigationView.getHeaderView(0).findViewById(R.id.icon_image);
        TextView nav_name = (TextView) navigationView.getHeaderView(0).findViewById(R.id.usr_name);
        TextView nav_phone = (TextView)navigationView.getHeaderView(0).findViewById(R.id.usr_phone);
        //icon.setImageResource(R.mipmap.ic_launcher);
        final Intent intent = getIntent();
        user_name = intent.getStringExtra("yourname");

        nav_name.setText(user_name);
        nav_phone.setText(Info.current_user_phone);
        Glide.with(getApplicationContext()).load("http://"+Info.server_ip+"/huahua/userpic/" + user_name + ".jpg").signature(new StringSignature(UUID.randomUUID().toString())).into(icon);
        /****/
        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
        flower_title = (TextView) findViewById(R.id.title_flower);
        flower_title.setText("我的花园");
        btn_home = (Button) findViewById(R.id.nav_button);

        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
//        ActionBar actionBar = getSupportActionBar();
//
//        if (actionBar != null) {
//            actionBar.setDisplayHomeAsUpEnabled(true);
//            actionBar.setHomeAsUpIndicator(R.drawable.ic_home);
//        }
        navigationView.setCheckedItem(R.id.user_change_phone);
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {

                drawerLayout.closeDrawers();
                switch (item.getTitle().toString()){
                    case "退出当前用户":
                        SharedPreferences.Editor editor = getSharedPreferences("login_date", MODE_PRIVATE).edit();
                        editor.putString("login_name","");
                        editor.apply();
                        Intent logoff_intent = new Intent(FlowerActivity.this, MainActivity.class);
                        startActivity(logoff_intent);
                        overridePendingTransition(android.R.anim.slide_in_left,android.R.anim.slide_out_right);
                        break;
                    case "更改密码":
                        Intent change_password_intent = new Intent(FlowerActivity.this, Change_user_password.class);
                        startActivity(change_password_intent);
                        break;
                    case "更换用户头像":
                        startActivity(new Intent(FlowerActivity.this, Change_user_touxiang.class));
                        break;
                    case "修改绑定手机号":
                        startActivity(new Intent(FlowerActivity.this, Change_user_phone.class));
                        break;
                }
                return  true;
            }
        });
        btn_home.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                drawerLayout.openDrawer(GravityCompat.START);
            }
        });
        huoquflower();
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycle_view);
        GridLayoutManager layoutManager = new GridLayoutManager(this, 1);
        recyclerView.setLayoutManager(layoutManager);
        flowerAdapter = new FlowerAdapter(flowerList);
        recyclerView.setAdapter(flowerAdapter);
        swipeRefresh = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh);
        swipeRefresh.setColorSchemeResources(R.color.colorPrimary);
        swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshFlower();
            }
        });

        float_btn = (FloatingActionButton) findViewById(R.id.fab);
        float_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent creat_mac_intent = new Intent(FlowerActivity.this, Creat_mac_one.class);
                startActivity(creat_mac_intent);

            }
        });
    }


}
